package weiyao.xinxidasai.config.WebConfig;

import cn.hutool.json.JSONUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import weiyao.xinxidasai.DTO.Result;
import weiyao.xinxidasai.Utils.ThreadLocal.UserHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true; // 放行预检请求
        }
        // 1. 判断是否需要拦截（ThreadLocal中是否有用户）
        if (UserHolder.getUser() == null) {
            // 2. 没有用户，需要拦截，设置状态码
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

            // 3. 返回JSON格式的错误信息
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSONUtil.toJsonStr(Result.fail("未登录或登录已过期")));
            writer.close();
            return false;
        }
        // 4. 有用户，则放行
        return true;
    }
}